<template>
<div>
    <!-- 面包屑组件 -->
    <breadcrumb :navData="navData"></breadcrumb>

     <!-- Card 卡片 -->
    <el-card>
        <!-- 添加分类按钮 -->
        <el-button type="primary" @click="onAddCateBtn">添加分类</el-button>
        
        <!-- 列表 -->
        <el-table :data="list" border stripe style="width: 100%;" row-key="cat_id">
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="cat_name" label="分类名称">
            </el-table-column>
            <el-table-column prop="cat_deleted" label="是否有效">
                <template slot-scope="scope">
                    <i style="color:green;" v-if="!scope.row.label" class="el-icon-success"></i>
                    <i style="color:red;" v-else class="el-icon-error"></i>
                </template>
            </el-table-column>
            <el-table-column prop="cat_level" label="排序">
                <template slot-scope="scope">
                    <el-tag size="mini" v-if="scope.row.cat_level === 0" effect="dark">一级</el-tag>
                    <el-tag size="mini" v-if="scope.row.cat_level === 1" type="success" effect="dark">二级</el-tag>
                    <el-tag size="mini" v-if="scope.row.cat_level === 2" type="warning" effect="dark">三级</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 编辑 -->
                    <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="onEditCate(scope.row)">编辑</el-button>
                    <!-- 删除 -->
                    <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="onDeleteCate(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <!-- 添加商品分类的模态框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialog"
            >
            <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="addForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="分类父级">
                    <el-cascader
                    @change="onCascaderChange"
                    v-model="selectKeys"
                    :options="options"
                    :props="cascaderProps"
                    clearable></el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialog = false">取 消</el-button>
                <el-button type="primary" @click="onAddSureCate">确 定</el-button>
            </span>
        </el-dialog>

        <!--修改分类的模态框-->
        <el-dialog
            title="修改分类"
            :visible.sync="editDialogVisible"
            width="60%">
            <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
                <!--分类名称-->
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="editForm.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible= false">取 消</el-button>
                <el-button type="primary" @click="onEditBtnClick">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
</div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      //面包屑数据
      navData: ["商品管理", "分类管理"],
      list: [],
      //查询所有分类的参数
      type: "", //分类级别
      pagenum: 1, //当前的页码  默认是第1页  不可以为空
      pagesize: 5, //每页显示的条数 默认是5条   不可以为空
      total: 0, //总数量

      //添加的数据
      addDialog: false, //添加的弹框
      addForm: {
        //添加的数据
        cat_pid: "0",
        cat_name: "",
        cat_level: "0"
      },
      addRules: {
        //添加的规则
        cat_name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      },

      //编辑的数据
      editDialogVisible: false, //编辑的弹框
      editForm: {
        //分类名称
        cat_name: ""
      },
      //编辑的规则
      editRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      curEditId: "",

      //分类级联选择器数据
      options: [],
      //分类级联选择器配置项
      cascaderProps: {
        checkStrictly: true,
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //分类级联选择器，当前被选中的节点id
      selectKeys: []
    };
  }, // 组件方法

  methods: {
    //请求数据列表
    async getList() {
      let res = await this.$http.get("/categories", {
        params: {
          type: this.type,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      });
      console.log("res_list", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.list = res.data.result;
      this.total = res.data.total;
    },

    //点击添加分类按钮
    async onAddCateBtn() {
      let res = await this.$http.get("/categories", {
        params: { type: 2 }
      });
      console.log("add_cate", res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options = res.data;
      this.addDialog = true;
    },
    //父分类级联选择器change事件
    onCascaderChange() {
      console.log("当前被选中的节点id", this.selectKeys);
      if (this.selectKeys.length) {
        this.addForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
        this.addForm.cat_level = this.selectKeys.length;
      } else {
        this.addForm.cat_pid = "0";
        this.addForm.cat_level = "0";
      }
    },
    //点击确定添加分类
    async onAddSureCate() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return;
        //通过校验
        let res = await this.$http.post("categories", this.addForm);
        this.addForm.cat_name = "";
        this.selectKeys = [];
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.getList();
        this.$message.success(res.meta.msg);
        this.addDialog = false;
      });
    },

    //删除分类
    async onDeleteCate(row) {
      let result = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(result);
      if (result !== "confirm") return this.$message.info("取消删除");
      let res = await this.$http.delete(`categories/${row.cat_id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getList();
      this.$message.success(res.meta.msg);
    },


    //编辑分类
    onEditCate(row) {
      this.curEditId = row.cat_id;
      this.editForm.cat_name = row.cat_name;
      this.editDialogVisible = true;
    },
    //点击确定修改
    onEditBtnClick() {
      this.$refs.editFormRef.validate(async value => {
        if (!value) return;
        let res = await this.$http.put(
          `categories/${this.curEditId}`,
          this.editForm
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.getList();
        this.$message.success(res.meta.msg);
        this.editDialogVisible = false;
      });
    },

    // 分页
    handleSizeChange(newSize) {
      this.pagesize = newSize;
      this.getList();
    },
    handleCurrentChange(current) {
      this.pagenum = current;
      this.getList();
    }
  },

  created() {
    this.getList();
  }
};
</script> 

<style scoped>
</style>